package com.lehecai.core.queue.jms;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.lang.StringUtils;

import javax.jms.Queue;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 创建Queue
 * User: sunshow
 */
public abstract class AbstractJmsQueueFactoryBean<T> {

    private String globalPrefix;

    protected Map<T, Queue> instanceMap = new ConcurrentHashMap<T, Queue>();

    private Lock lock = new ReentrantLock();

    abstract protected String generateQueueName(T key);

    protected Lock getLock() {
        return lock;
    }

    protected Queue createInstance(T key) {
        return this.createQueueByName(this.generateQueueName(key));
    }

    protected Queue createQueueByName(String queue) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(this.getGlobalPrefix())) {
            sb.append(this.getGlobalPrefix());
        }
        sb.append(queue);
        return new ActiveMQQueue(sb.toString());
    }

    public Queue getInstance(T key) {
        Queue queue = instanceMap.get(key);

        if (queue == null) {
            lock.lock();
            queue = instanceMap.get(key);
            if (queue == null) {
                queue = this.createInstance(key);
                instanceMap.put(key, queue);
            }
            lock.unlock();
        }

        return queue;
    }

    public String getGlobalPrefix() {
        return globalPrefix;
    }

    public void setGlobalPrefix(String globalPrefix) {
        this.globalPrefix = globalPrefix;
    }
}
